package com.ai.web.servlet;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;

import org.apache.log4j.Logger;

import com.ai.web.weixin.WeixinContext;
import com.tiny.persistence.repository.impl.TinyApplicationContext;

/**
 * @author wushen
 */
public class InitServlet extends HttpServlet {

	private static final long serialVersionUID = -7704034054661745516L;
    private static Logger logger = Logger.getLogger(InitServlet.class);

	@Override
	public void init() throws ServletException {
		List<Map<String, Object>> list = TinyApplicationContext.getJdbcTemplateBean().queryForList("select id from bg_menu");
		if(list == null || list.size() == 0){
			initMethod("bg_menu", "bgMenu.sql");
			initMethod("bg_role", "bgRole.sql");
			initMethod("bg_role_menu", "bgRoleMenu.sql");
			initMethod("bg_user", "bgUser.sql");
			initMethod("wx_menu", "wxMenu.sql");
			initMethod("wx_role", "wxRole.sql");
			initMethod("wx_role_menu", "wxRoleMenu.sql");
			initMethod("wx_keyword_config", "wxKeywordConfig.sql");
		}
		System.setProperty ("jsse.enableSNIExtension", "false");
		WeixinContext.init();
	}

	private void initMethod(String tableName, String fileName) {

		// 初始化菜单
		List<String> sqlList = new ArrayList<String>();

		try {
			// 读文件内容
			File data = new File(this.getClass().getResource("/").getPath()
					+ "initDbSql/" + fileName);

			List<File> fileList = new ArrayList<File>();
			fileList.add(data);
			// fileList.add(wxMenu);

			for (File file : fileList) {
				InputStreamReader isr = new InputStreamReader(
						new FileInputStream(file), "utf-8");
				BufferedReader br = new BufferedReader(isr);

				String str = null;
				while ((str = br.readLine()) != null) {
					sqlList.add(str);
				}
				br.close();
				isr.close();
			}

		} catch (Exception ex) {
			ex.printStackTrace();
		}

		String[] menusql = new String[sqlList.size()];
		sqlList.toArray(menusql);
		TinyApplicationContext.getJdbcTemplateBean().batchUpdate(menusql);
		List<Map<String, Object>> bgMenulist = TinyApplicationContext
				.getJdbcTemplateBean().queryForList(
						"select * from " + tableName);
		printListContent(bgMenulist);

		logger.info("初始化菜单完毕");
	}

	/**
	 * 打印列表内容
	 * 
	 * @param list
	 */
	private void printListContent(List<Map<String, Object>> list) {

		for (Map<String, Object> map : list) {
			System.out.println(map.toString());
		}
	}
}
